package com.irdstudio.apicenter.gateway.web.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.irdstudio.apicenter.gateway.comm.MaccsPacket;
import com.irdstudio.apicenter.gateway.comm.MaccsPacketUtil;
import com.irdstudio.apicenter.gateway.util.PathUtil;

public class WebUploadUtil {
	
	/* 文本日志输出 */
	private static final Logger logger = LoggerFactory
			.getLogger(WebUploadUtil.class);
	
	/**
	 * 上传文件处理
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public final static MaccsPacket uploadFile(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		MaccsPacket backPacket = null;
		response.setContentType("text/html;charset=GBK");
		request.setCharacterEncoding("GBK");
		HttpSession session = request.getSession();
		session.setAttribute("progressBar", 0); // 定义指定上传进度的Session变量
		String error = "";
		int maxSize = 50 * 1024 * 1024; // 单个上传文件大小的上限
		DiskFileItemFactory factory = new DiskFileItemFactory(); // 基于磁盘文件项目创建一个工厂对象
		ServletFileUpload upload = new ServletFileUpload(factory); // 创建一个新的文件上传对象
		FileOutputStream fos =null;
		try {
			// 统计文件域个数及实际上传的文件个数
			int fileIndex = 0, fileUploadCount = 0;
			List items = upload.parseRequest(request);// 解析上传请求
			Iterator itr = items.iterator();// 枚举方法
			while (itr.hasNext()) {
				// 获取FileItem对象
				FileItem item = (FileItem) itr.next();
				// 判断是否为文件域
				if (!item.isFormField()) {
					fileIndex++;
					// 判断是否选择了文件,选择了则进行上传处理,否则不处理,跳过
					if (item.getName() != null && !item.getName().equals("")) {
						long upFileSize = item.getSize(); // 上传文件的大小
						String fileName = item.getName(); // 获取文件名
						logger.info("文件域[" + fileIndex + "],上传文件:"
								+ item.getName() + ",文件大小:" + item.getSize());
						if (upFileSize > maxSize) {
							error = "您上传的文件太大，请选择不超过50M的文件";
							break;
						}
						// 获取根目录对应的真实物理路径并构造文件对象
						String uploadPath = PathUtil.getProjectRootPath()
								+ "/upload";						
						File file = new File(uploadPath, fileName);
						InputStream is = item.getInputStream();
						int buffer = 1024; // 定义缓冲区的大小
						int length = 0;
						byte[] b = new byte[buffer];
						double percent = 0;
						fos = new FileOutputStream(file);
						while ((length = is.read(b)) != -1) {
							percent += length / (double) upFileSize * 100D; // 计算上传文件的百分比
							fos.write(b, 0, length); // 向文件输出流写读取的数据
							session.setAttribute("progressBar", Math
									.round(percent)); // 将上传百分比保存到Session中
						}
						fos.close();
						Thread.sleep(1000); // 线程休眠1秒
						fileUploadCount++;  // 文件上传数+1
					} else {
						// 说明该 文件域没有选择要上传的文件,跳过
						logger.info("文件域[" + fileIndex + "],没有选择要上传的文件!");
						continue;
					}
				}
			}
			// 如果文件域为0或实际上传的文件数为0,均说明没有上传文件,返回错误
			if (fileIndex == 0 || fileUploadCount == 0) {
				error = "没有选择上传文件！";
			}
		} catch (Exception e) {
			e.printStackTrace();
			error = "上传文件出现错误：" + e.getMessage();
		} finally {
			try {
				if (fos != null) {
					fos.close();
					fos=null;
				}
			} catch (Exception e2) {
			}
			if (!"".equals(error)) {
				backPacket = MaccsPacketUtil.makeFailurePacket(error);
			} else {
				backPacket = MaccsPacketUtil.makeSimpleSuccessPacket("文件上传成功！");
			}
		}
		return backPacket;
	}	
}
